import MySQLdb

HOST = 'localhost'
DATABASE = 'test_smart'
USER = 'root'
PASSWORD = 'Welcome01'


class DatabaseConnection:
    def __init__(self, log):
        self.log = log
        self.open_database_connection()

    def open_database_connection(self):
        try:
            self.conn = MySQLdb.connect(host=HOST, user=USER, passwd=PASSWORD,db=DATABASE)
            self.cur = self.conn.cursor()
            self.log._log('INFO: Connection to database succeed')
        except Exception, e:
            self.log._log('ERROR: Connection to database failed, exception [%s]' % e)
            raise Exception

    def close_database_connection(self):
        try:
            self.cur.close()
            self.conn.close()
        except:
            pass

    def execute_sql_statement(self, sql_statement):
        try:
            self.cur.execute(sql_statement)
            self.conn.commit()
            self.log._log('INFO: Execute SQL statement [%s] succeed' % sql_statement)
            return self.cur
        except Exception, e: # just logging with error info and continue execution
            self.log._log('ERROR: Execute SQL statement [%s] failed, exception [%s]' % (sql_statement, e))